/*
* 1videoConference -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, Adiance Technologies Pvt. Ltd.
*
* Hardik Sanghvi <hardik.sanghvi @adiance.com>
*
* See http://www.1videoconference.org for more information about
* the 1videoConference project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Windows;
using System.IO;
using ZipInfo;
using NetPeerService;
using System.Data;

namespace _videoConference.BAL
{   
    public static class UserInfo
    {
        public static string Password = "";

        public static int Number;

        public static string UserName = "";
        public static string MyRole = "";
        public static string MeetingID = "";

        public static string CreUserName = "1videoConference";
        public static string CrePassword = "resiprocket";
        public static string CreMachName = "";

        public static string ConSMTPServer = "";
        public static string ConSMTPPort = "";
        public static string ConSMTPUserName = "";
        public static string ConSMTPPassword = "";
        public static string ConSMTPSSL = "";
        public static string ConAsteriskServer = "";
        public static string ConSiteURL = "";
        public static string strMeetingMode = "";
        public static string MyCurrentPage = "";
        public static string ConnectionString = "";
        
        static string MyURL = ""; 
        static string[] URLParams;
      
        public static IsvcLoginInfoChannel channelLoginInfo;
        public static NetPeerClient clientLoginInfo;
        public static object objectLoginInfo = null;

        public static CliSvcZipInfo objSvcZipInfo = null;
        public static Fileuploadcode fuc= null;

        public static bool moveAhead = true;

        public static string crtmeeting = "";
        public static string moduleid = "";

        public static bool zipextract = true;

        public static string[] DBCredentials = new string[3];

        public static DataSet ds = new DataSet();

        public static IAddPage ia = new IAddPage();

        public static void Initialize()
        {
          
            #region Deployment
            try
            {
                CreMachName = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri.AbsoluteUri.ToString().Replace("http://", "");                
                CreMachName = UserInfo.CreMachName.Substring(0, UserInfo.CreMachName.IndexOf('/'));                
                MyURL = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri.AbsoluteUri.ToString();                
                if (MyURL.IndexOf("?") > 0)
                {                    
                    MyURL = DeCodeString(MyURL).Split('?')[1];
                    URLParams = MyURL.Split(',');

                    for (int i = 0; i < URLParams.Length; i++)
                    {
                        if (URLParams[i].Split('=')[0].ToLower() == "uname")
                        {
                            UserName = URLParams[i].Split('=')[1];
                        }
                        else if (URLParams[i].Split('=')[0].ToLower() == "role")
                        {
                            MyRole = URLParams[i].Split('=')[1];
                        }
                        else if (URLParams[i].Split('=')[0].ToLower() == "mid")
                        {
                            MeetingID = URLParams[i].Split('=')[1];
                        }
                    }
                }
                if (UserName == "")
                {
                    UserName = Environment.MachineName;
                }
                if (MyRole == "")
                {
                    MyRole = "Host";
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--UserInfo.cs--:--Initialize()1--:--");
                clsUtility.LogException = exp;                
                UserName = Environment.MachineName;
                MyRole = "Host";
                CreMachName = "192.168.1.186";
                MeetingID = "";
            }
            if (MeetingID != "")
            {
                strMeetingMode = "Meeting Mode";
            }
            else
            {
                strMeetingMode = "Design Mode";
            }
                #endregion

            #region Services
            try
            {           
                objectLoginInfo = new CsvcLoginInfo();
                clientLoginInfo = new NetPeerClient();

                ((CsvcLoginInfo)objectLoginInfo).EntsvcJoin += new CsvcLoginInfo.DelsvcJoin(UserInfo_EntsvcJoin);
                ((CsvcLoginInfo)objectLoginInfo).EntsvcGetDatabaseIP += new CsvcLoginInfo.DelsvcGetDatabaseIP(UserInfo_EntsvcGetDatabaseIP);
                ((CsvcLoginInfo)objectLoginInfo).EntsvcSetDatabaseIP += new CsvcLoginInfo.DelsvcSetDatabaseIP(UserInfo_EntsvcSetDatabaseIP);
                ((CsvcLoginInfo)objectLoginInfo).EntsvcSetMID += new CsvcLoginInfo.DelsvcSetMID(UserInfo_EntsvcSetMID);
                ((CsvcLoginInfo)objectLoginInfo).EntsvcUnSetMID += new CsvcLoginInfo.DelsvcUnSetMID(UserInfo_EntsvcUnSetMID);
                ((CsvcLoginInfo)objectLoginInfo).EntsvcUnJoin += new CsvcLoginInfo.DelsvcUnJoin(UserInfo_EntsvcUnJoin);
                channelLoginInfo = (IsvcLoginInfoChannel)clientLoginInfo.OpenClient<IsvcLoginInfoChannel>("net.tcp://" + CreMachName + ":2500/LoginInfo", "LoginInfoMesh", ref objectLoginInfo);
                channelLoginInfo.svcJoin(UserName);

                if (strMeetingMode == "Design Mode")
                {
                    fuc = new Fileuploadcode();
                    fuc.servercred();
                }

                #region DirectoryCreation
                System.Reflection.Assembly ass = System.Reflection.Assembly.GetAssembly(typeof(UserInfo));
                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Zip Files")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Zip Files"));
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Temp")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Temp"));                   
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Presentation Layer")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Presentation Layer"));
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Data Layer")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Data Layer"));
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Business Layer")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Business Layer"));
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Image")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Image"));
                }

                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"SQL Scripts")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"SQL Scripts"));
                }
                if (!Directory.Exists(ass.Location.Replace("1videoConference.BAL.dll", @"Zip Temp")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("1videoConference.BAL.dll", @"Zip Temp"));
                }
                #endregion

                try
                {
                    channelLoginInfo.svcGetDatabaseIP(UserName, MeetingID);
                }
                catch (Exception exp)
                {
                    //MessageBox.Show("GetDatabaseIP:" + exp.Message);
                }               
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--UserInfo.cs--:--Initialize()2--:--");
                clsUtility.LogException = exp;
            }
            #endregion
        }

        static void UserInfo_EntsvcUnJoin(string UName)
        {
            
        }

        static void UserInfo_EntsvcUnSetMID(string mid)
        {
            
        }

        static void UserInfo_EntsvcSetMID(string mid)
        {
            
        }

        static void UserInfo_EntsvcSetDatabaseIP(string[] DatabaseIP, string UName, string mid)
        {
            if (UserName == UName && MeetingID == mid)
            {                
                DBCredentials = DatabaseIP;
                if (DBCredentials != null)
                {
                    ConnectionString = "Server=" + DBCredentials[0] + "\\SQLExpress;Initial Catalog=Videoconference;User Id=" + DBCredentials[1] + ";Password=" + DBCredentials[2] + ";Integrated Security=False";
                }
                else
                {
                    MessageBox.Show("Database credentials did not match");
                }

                DAL.Database.conStr = ConnectionString;

                ds = ia.getconfig();
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        switch (ds.Tables[0].Rows[i][0].ToString())
                        {
                            case "SMTPServer":
                                UserInfo.ConSMTPServer = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "SMTPPort":
                                UserInfo.ConSMTPPort = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "SMTPUserName":
                                UserInfo.ConSMTPUserName = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "SMTPPassword":
                                UserInfo.ConSMTPPassword = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "SMTPSSL":
                                UserInfo.ConSMTPSSL = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "AsteriskServer":
                                UserInfo.ConAsteriskServer = ds.Tables[0].Rows[i][1].ToString();
                                break;

                            case "SiteURL":
                                UserInfo.ConSiteURL = ds.Tables[0].Rows[i][1].ToString();
                                break;
                        }
                    }
                }
            }
        }

        static void UserInfo_EntsvcGetDatabaseIP(string UName, string mid)
        {
            
        }

        static void UserInfo_EntsvcJoin(string UName)
        {
            
        }

        static string EnCodeString(string str)
        {
            try
            {
                int j = 0;

                Byte[] encodedBytes = ASCIIEncoding.ASCII.GetBytes(str);
                Byte[] ans = new Byte[encodedBytes.Length];
                foreach (Byte b in encodedBytes)
                {

                    int i = Convert.ToInt32(b);

                    if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122))
                    {
                        i += 4;
                        if ((i > 90 && i <= 97) || (i > 122 && i <= 129))
                            i = i - 26;

                    }
                    else if (i >= 48 && i <= 57)
                    {
                        i += 7;
                        if (i > 57)
                            i = i - 10;
                    }
                    else
                    {
                        if (i == 61)
                            i = 44;
                        else if (i == 44)
                            i = 61;
                    }

                    ans[j++] = Convert.ToByte(i);
                }
                return ASCIIEncoding.ASCII.GetString(ans);
            }
            catch(Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--UserInfo.cs--:--Encodestring()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--UserInfo.cs--:--EnCodeString()--:--" + exp.Message);
                return null;
            }
        }

        static string DeCodeString(string str)
        {
            try
            {
                int j = 0;

                Byte[] encodedBytes = ASCIIEncoding.ASCII.GetBytes(str);
                Byte[] ans = new Byte[encodedBytes.Length];
                foreach (Byte b in encodedBytes)
                {

                    int i = Convert.ToInt32(b);

                    if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122))
                    {
                        i -= 4;
                        if ((i < 65 && i >= 61) || (i < 97 && i >= 93))
                            i = i + 26;

                    }
                    else if (i >= 48 && i <= 57)
                    {
                        i -= 7;
                        if (i < 48)
                            i = i + 10;
                    }

                    else
                    {
                        if (i == 61)
                            i = 44;
                        else if (i == 44)
                            i = 61;
                    }

                    ans[j++] = Convert.ToByte(i);
                }
                return ASCIIEncoding.ASCII.GetString(ans);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--UserInfo.cs--:--Decodestring()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--UserInfo.cs--:--DeCodeString()--:--" + exp.Message);
                return null;
            }
        }

        public static void closelogininfo()
        {
            try
            {
                if (objectLoginInfo != null)
                {
                    if (channelLoginInfo.State != CommunicationState.Closed)
                    {
                        channelLoginInfo.Close();
                        channelLoginInfo.Dispose();
                    }
                    objectLoginInfo = null;
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--UserInfo.cs--:--closelogininfo()--:--");
                clsUtility.LogException = exp;
            }
        }
    }
}
